package com.aliang.service.impl;

import org.springframework.beans.factory.annotation.Autowired;

import com.aliang.service.JedisService;

import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;

public class JedisServiceImpl implements JedisService {

	private interface Function<T,E>{
		
		T callback(E e);

	}
	
	@Autowired
	ShardedJedisPool shardedJedisPool;
	
	private <T> T execute(Function<T,ShardedJedis> fun){
		
		ShardedJedis shardedJedis = shardedJedisPool.getResource() ;
		
		return fun.callback(shardedJedis);
		
	}

	@Override
	public String set(final String key, final String value) {

		return this.execute(new Function<String,ShardedJedis>(){
			
			@Override
			public String callback(ShardedJedis e){
				//添加缓存
				return e.set(key, value);
				
			}
			
		});
		
	}
	
	@Override
	public String set(final String key,final String value,final Integer seconds) {
		return this.execute(new Function<String,ShardedJedis>(){

			@Override
			public String callback(ShardedJedis e) {
				//添加缓存并设置有效时间
				String result =  e.set(key, value);
				e.expire(key, seconds);
				return result;
			}
			
		}) ;
	}

	@Override
	public String get( final String key) {
		return this.execute(new Function<String,ShardedJedis>(){

			@Override
			public String callback(ShardedJedis e) {
				//获取缓存
				return e.get(key);
			}
			
		});
	}

	@Override
	public Long del(final String key) {
		
		return this.execute(new Function<Long,ShardedJedis>(){

			@Override
			public Long callback(ShardedJedis e) {
				//删除缓存
				return e.del(key);
			}
			
		});
		
	}
	
	
	
	

}
